package com.youxin.user.resolver;


import com.youxin.context.BaseContextHandler;
import com.youxin.user.annotation.LoginUser;
import com.youxin.user.dubbo.UserResolveApi;
import com.youxin.user.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Token转化SysUser
 *
 * @author zuihou
 * @date 2018/12/21
 */
public class ContextArgumentResolver implements HandlerMethodArgumentResolver {

    private static final Logger log = LoggerFactory.getLogger(ContextArgumentResolver.class);
    private UserResolveApi userResolveApi;

    public ContextArgumentResolver(UserResolveApi userResolveApi) {
        this.userResolveApi = userResolveApi;
    }

    /**
     * 入参筛选
     *
     * @param mp 参数集合
     * @return 格式化后的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter mp) {
        return mp.hasParameterAnnotation(LoginUser.class) && mp.getParameterType().equals(SysUser.class);
    }

    /**
     * @param methodParameter       入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest      web相关
     * @param webDataBinderFactory  入参解析
     * @return 包装对象
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        String userNo = BaseContextHandler.getUserNo();
        String account = BaseContextHandler.getAccount();
        String name = BaseContextHandler.getName();
        //以下代码为 根据 @LoginUser 注解来注入 SysUser 对象
        SysUser user = new SysUser();
        user.setUserNo(userNo);
        user.setUserName(account);
        user.setNickName(name);

        try {
            LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class);
            boolean isFull = loginUser.isFull();

            if (isFull ) {
                SysUser result = userResolveApi.getById(userNo);
                if (result != null) {
                    return result;
                }
            }
        } catch (Exception e) {
            log.warn("注入登录人信息时，发生异常. --> {}", user, e);
        }

        return user;
    }
}
